﻿class GameManager {
    private _snake: Snake;
    private _food: Food;
    private _ctx: CanvasRenderingContext2D;
    private _interval: any;

    constructor(ctx: CanvasRenderingContext2D) {
        this._ctx = ctx;
        this._snake = new Snake(2);
        this._food = new Food();
        this._food.Position = this._food.makePoint();
    }

    startGame() {
        //键盘事件。
        document.addEventListener("keydown", e => this.keyDown(e));

        //启动线程定时更新状态
        this._interval = setInterval(() => this.runEngine(), 500);
    }

    draw() {
        let old = this._ctx;
        this._ctx.fillStyle = "#FFFFFF";
        this._ctx.fillRect(0, 0, 600, 450);  
        this._ctx.fillStyle = old;

        this._snake.draw(this._ctx);

        this._food.drawFood(this._ctx);

        if (this._snake.isOver()) {
            clearInterval(this._interval);
            alert("Game Over!");
        }
    }

    runEngine() {
        this._snake.move();

        let foodPos = this._food.Position;
        let snakeHead = this._snake.Head;
        if (foodPos.x == snakeHead.x
            && foodPos.y == snakeHead.y) {
            console.log("eat one");
            this._snake.eatFood();

            this._food = new Food();
            this._food.Position = this._food.makePoint();
        }

        this.draw();
    }

    keyDown(e: KeyboardEvent) {
        console.log("keyCode" + e.keyCode);
        switch (e.keyCode) {
            case KeyCodes.left:
                if (this._snake.way != DIRECTION.RIGHT) {
                    this._snake.way = DIRECTION.LEFT;
                }
                break;
            case KeyCodes.up:
                if (this._snake.way != DIRECTION.BOTTOM) {
                    this._snake.way = DIRECTION.TOP;
                }
                break;
            case KeyCodes.right:
                if (this._snake.way != DIRECTION.LEFT) {
                    this._snake.way = DIRECTION.RIGHT;
                }
                break;
            case KeyCodes.down:
                if (this._snake.way != DIRECTION.TOP) {
                    this._snake.way = DIRECTION.BOTTOM;
                }
                break;
        }
    }
}